package com.linkstec.xml;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlTest{


	public static void main(String[] args) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

        Document doc = null;
		try {
			doc = db.parse(new File(XmlTest.class.getResource("/").getPath() + "student.xml"));
		} catch (SAXException | IOException e) {
			e.printStackTrace();
		}

        // System.out.println(doc.getXmlEncoding());
        // System.out.println(doc.getXmlVersion());
        // System.out.println(doc.getXmlStandalone());

        // 得到根节点
        Element root = doc.getDocumentElement();
        System.out.println("rootTagName: " + root.getTagName());

        // 得到根节点的子节点，注意此处的空格也被计为子节点
        NodeList list = root.getChildNodes();
        System.out.println("root child Count: " + list.getLength());

        for (int i = 0; i < list.getLength(); i++)
        {
            System.out.println("item " + i + ": getNodeName: "
                    + list.item(i).getNodeName());
        }

        System.out.println("------------NodeType and Value----------------");

        for (int i = 0; i < list.getLength(); i++)
        {
            Node n = list.item(i);

            // getNodeType返回的是short型的常量值，文档中有定义每个值对应的类型
            System.out.println("getNodeType: " + n.getNodeType()
                    + " , getNodeValue: " + n.getNodeValue());
        }

        System.out.println("-----------getTextContent----------------");

        for (int i = 0; i < list.getLength(); i++)
        {
            Node n = list.item(i);

            System.out.println(n.getTextContent());
        }

        System.out.println("-------------属性测试----------------");

        NodeList nodeList = doc.getElementsByTagName("学生");

        for (int i = 0; i < nodeList.getLength(); i++)
        {
            NamedNodeMap nnm = nodeList.item(i).getAttributes();

            String attrName = nnm.item(0).getNodeName();
            System.out.print("node " + i + ": " + attrName);
            System.out.print("=");

            // 属性的名字和值即为本身的名字和值
            String attrValue = nnm.item(0).getNodeValue();
            System.out.println(attrValue);
        }

	}
}
